package com.lzw.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.lzw.blog.admin.mapper.TagMapper;
import com.lzw.blog.admin.model.params.PageParam;

import com.lzw.blog.admin.pojo.Tag;
import com.lzw.blog.admin.vo.PageResult;
import com.lzw.blog.admin.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagService {


    @Autowired
    private TagMapper tagMapper;

    public Result listTag(PageParam pageParam) {
        Page<Tag> page = new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize());
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParam.getQueryString())) {
            queryWrapper.like(Tag::getTagName, pageParam.getQueryString());
        }
        Page<Tag> tagPage = tagMapper.selectPage(page, queryWrapper);
        PageResult<Tag> pageResult = new PageResult<>();
        pageResult.setList(tagPage.getRecords());
        pageResult.setTotal(tagPage.getTotal());
        return Result.success(pageResult);
    }

    public Result add(Tag tag) {
        this.tagMapper.insert(tag);
        return Result.success(null);
    }

    public Result update(Tag tag) {
        this.tagMapper.updateById(tag);
        return Result.success(null);
    }

    public List<Tag> findTagsByArticleId(Long articleId) {
        //mybatis无法进行多表查询
        return tagMapper.findTagsByArticleId(articleId);
    }

    public Result delete(Long id) {
        this.tagMapper.deleteById(id);
        return Result.success(null);
    }
}
